package com.zsj.service;

import com.zsj.config.ConfigBean;
import com.zsj.enums.OrderStatusEnum;
import com.zsj.mysql.entity.DyMobileRecharge;
import com.zsj.mysql.service.IDyMobileRechargeService;
import com.zsj.util.DateUtil;
import com.zsj.util.MoneyUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Description:
 * @Author:
 * @Date:
 */
@Slf4j
@Service
public class BatchService {

    @Autowired
    private IDyMobileRechargeService rechargeService;

    @Autowired
    private ConfigBean configBean;

    public boolean createFile(String date) {
        log.info("开始生成对账文件");
        try {
            for (String appId : configBean.getAppIds()) {
                log.info("查询appId:{}的数据", appId);
                // 对账文件是根据终态日期筛选数据，存在跨月的情况，所以先查询上一个月的数据
                List<DyMobileRecharge> list = new ArrayList<>();
                list.addAll(rechargeService.getFinishByDayAndAppId(DateUtil.getLastMonth(), Integer.valueOf(date), appId));
                // 再查询本月的数据
                list.addAll(rechargeService.getFinishByDayAndAppId(date.substring(0, 6), Integer.valueOf(date), appId));
                log.info("查询appId:{}在{}的数据量为:{}", appId, date, list.size());
                log.info("开始写入文件");
                StringBuilder head = new StringBuilder();
                head.append("字节订单号").append(",")
                        .append("供应商/运营商订单号").append(",")
                        .append("供应商/运营商商⼾号(appid)").append(",")
                        .append("订单提交时间").append(",")
                        .append("订单终态时间").append(",")
                        .append("产品⾯额(分)").append(",")
                        .append("产品实付价格（分）").append(",")
                        .append("订单状态").append(",")
                        .append("备注（可选）").append("\r\n");
                StringBuilder body = new StringBuilder();
                list.forEach(entity -> {
                    String timeDate = DateUtil.getDateTimeByTimestamp(entity.getTimestamp());
                    if(StringUtils.isBlank(timeDate)) {
                        timeDate = DateUtil.getDateTimeByDate(entity.getCreateTime());
                    }

                    OrderStatusEnum orderStatus =  OrderStatusEnum.findByCode(entity.getOrderStatus() + "");
                    String status = "";
                    if(Objects.nonNull(orderStatus)) {
                        status = orderStatus.getMsg();
                    }

                    body.append(entity.getChargeNo()).append(",")
                            .append(entity.getChannelChargeNo()).append(",")
                            .append(entity.getAppId()).append(",")
                            .append(timeDate).append(",")
                            .append(entity.getFinishTime()).append(",")
                            .append(entity.getProductDenomination()).append(",")
                            .append(MoneyUtil.haoToFen(entity.getContractPrice())).append(",")
                            .append(status).append(",")
                            .append("").append("\r\n");
                });
                Path directoryPath = Paths.get(configBean.getCreateFilePath(), appId);
                Path filePath = directoryPath.resolve(date + ".csv");
                try {
                    Files.createDirectories(directoryPath);
                    Files.write(filePath, head.append(body).toString().getBytes(StandardCharsets.UTF_8));
                } catch (IOException ie) {
                    log.error("appId{}写入文件失败", appId, ie);
                }
            }

            return true;
        } catch (Exception e) {
            log.error("生成对账文件异常", e);
            return false;
        }
    }
}
